package com.maple.springbootinit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.maple.springbootinit.api.OpenAIAPI;
import com.maple.springbootinit.common.BaseResponse;
import com.maple.springbootinit.common.ErrorCode;
import com.maple.springbootinit.common.OpenApiResponse;
import com.maple.springbootinit.common.ResultUtils;
import com.maple.springbootinit.exception.BusinessException;
import com.maple.springbootinit.model.dto.chat.AiChatQueryRequest;
import com.maple.springbootinit.model.dto.chat.AiChatMessage;
import com.maple.springbootinit.model.entity.AiChat;
import com.maple.springbootinit.model.entity.User;
import com.maple.springbootinit.service.ChatService;
import com.maple.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/chat")
@Slf4j
public class AiCharController {
//    @Resource
//    private WebSocket webSocket;
    @Resource
    private ChatService chatService;
    @Resource
    private UserService userService;
    /// 推送数据到websocket客户端 接口
    @Resource
    private OpenAIAPI openAi;

    @PostMapping("add/message")
    public BaseResponse<AiChat>sendMessage(@RequestBody AiChatMessage aiChatMessage, HttpServletRequest request) throws IOException {
        if (aiChatMessage == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
//        return null;
//        String tmp = JSON.(aiChatMessage.getMessage());
//        tmp = "解释代码:\\n\\\"max-w-full mx-auto flex flex-col items-center px-4 space-y-4\\\"";
        String result = openAi.getChatGptResponse(aiChatMessage.getChatId(), JSON.toJSONString(aiChatMessage.getMessage()));
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
        // 获取 message 中的 content
        String content = jsonObject.getAsJsonArray("choices")
                .get(0)
                .getAsJsonObject()
                .getAsJsonObject("message")
                .get("content")
                .getAsString();

        AiChat aiChat = AiChat.builder()
                .message(aiChatMessage.getMessage())
                .chatId(aiChatMessage.getChatId())
                .userId(loginUser.getId())
                .genResult(content)
                .execMessage("")
                .status("succeed")
                .build();

        chatService.save(aiChat);
        return ResultUtils.success(aiChat);
    }

    @PostMapping("my/list/message")
    public BaseResponse<List<AiChat>>ChatMessageByList(@RequestBody AiChatQueryRequest aiChatQueryRequest, HttpServletRequest request){
        if (aiChatQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        aiChatQueryRequest.setUserId(loginUser.getId());
        List<AiChat> list = chatService.list(getQueryWrapper(aiChatQueryRequest));
        return ResultUtils.success(list);
    }
    private QueryWrapper<AiChat> getQueryWrapper(AiChatQueryRequest aiChatQueryRequest) {

        QueryWrapper<AiChat> queryWrapper = new QueryWrapper<>();
        if (aiChatQueryRequest == null) {
            return queryWrapper;
        }
        Long id = aiChatQueryRequest.getId();
        Long userId = aiChatQueryRequest.getUserId();
        String chatId = aiChatQueryRequest.getChatId();
        String status = aiChatQueryRequest.getStatus();
        queryWrapper.eq(ObjectUtils.isNotEmpty(id) && id > 0, "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(StringUtils.isNotBlank(chatId), "chatId", chatId);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
//        queryWrapper.eq("isDelete", false);
        return queryWrapper;
    }

}
